﻿using System;
using System.Collections.Generic;

namespace XmlStudio.Utilities {
    /// <summary>
    /// Helper comparer for lambda expressions.
    /// </summary>
    /// <typeparam name="T">Type.</typeparam>
    public class LambdaComparer<T> : IEqualityComparer<T> {
        private readonly Func<T, T, bool> _lambdaComparer;
        private readonly Func<T, int> _lambdaHash;

        /// <summary>
        /// Initializes a new instance of the <see cref="LambdaComparer{T}"/> class.
        /// </summary>
        /// <param name="lambdaComparer">Lambda comparer.</param>
        public LambdaComparer(Func<T, T, bool> lambdaComparer) :
            this(lambdaComparer, o => o.GetHashCode()) {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="LambdaComparer{T}"/> class.
        /// </summary>
        /// <param name="lambdaComparer">Lambda comparer.</param>
        /// <param name="lambdaHash">Lambda hash.</param>
        public LambdaComparer(Func<T, T, bool> lambdaComparer, Func<T, int> lambdaHash) {
            if(lambdaComparer == null)
                throw new ArgumentNullException("lambdaComparer");
            if(lambdaHash == null)
                throw new ArgumentNullException("lambdaHash");
            _lambdaComparer = lambdaComparer;
            _lambdaHash = lambdaHash;
        }

        /// <summary>
        /// Equalses the specified x.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        /// <returns></returns>
        public bool Equals(T x, T y) {
            return _lambdaComparer(x, y);
        }

        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        /// <param name="obj">The obj.</param>
        /// <returns>
        /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. 
        /// </returns>
        public int GetHashCode(T obj) {
            return _lambdaHash(obj);
        }
    }
}
